package com.example.demo.controller;

import com.example.demo.entity.BookInfo;
import com.example.demo.entity.Orders;
import com.example.demo.pay.Alipay;
import com.example.demo.pay.PayContext;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.OrderDetailService;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

import java.awt.print.Book;
import java.util.List;

@Controller
@RequestMapping("/payment")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private Alipay alipay;

    @RequestMapping("/{orderId}/{payMethod}")
    public String payOrders(@PathVariable(name = "orderId")String orderId, @PathVariable(name = "payMethod") Integer payMethod, HttpServletResponse response) throws Exception {


        if(payMethod==2)
            System.out.println("Alipay!");


        BSResult result=orderService.findOrdersByOrderId(orderId);

        Orders order= (Orders) result.getData();

        List<BookInfo> bookInfos=orderDetailService.findBookInfoByOrderId(orderId);

        PayContext payContext=new PayContext();
        payContext.setBookInfos(bookInfos);
        payContext.setResponse(response);
        payContext.setOrder(order);

        alipay.pay(payContext);


        return "pay_success";
    }

    /*

    @param out_trade_no  order id
    total_amount     total price

     */

    @RequestMapping("/return")
    public String orderSuccessReturn(String out_trade_no,String total_amount,String body,Model model){



        model.addAttribute("body", body);
        model.addAttribute("total_amount", total_amount);

        BSResult result=orderService.findOrdersByOrderId(out_trade_no);
        Orders order= (Orders) result.getData();

        List<BookInfo> bookInfos=orderDetailService.findBookInfoByOrderId(order.getOrderId());

        PayContext payContext=new PayContext();
        payContext.setBookInfos(bookInfos);
        payContext.setOrder(order);


        orderService.updateOrdersAfterPay(payContext);
        return "pay_success";
    }

    @RequestMapping("/notify")
    public void notifyUrl(){

        System.out.println("notify--------------------------");



    }
}
